/****************************************************
          File Name:sem_init.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 20 Sep 2014 07:44:58 PM CST
*****************************************************/

#include "posix_ipc.h"
#include <pthread.h>

static sem_t sem;       /* glob value for main thread and child thread */
static int glob=0;        /* loop in fun() */

void *fun(void *number)
{
    int loop,local,i;
    loop=*((int *)number);

    for(i=0;i<loop;i++)
    {
        if(sem_wait(&sem)==-1)
            err("wait");
        local=glob;
        local++;
        glob=local;
        if(sem_post(&sem)==-1)
            err("post");
    }
    return NULL;        /* (void *) */
}

int main(int argc, char *argv[])
{
    int loop=10000000;
    pthread_t tid1,tid2;
    int status;
    
    if(sem_init(&sem,0,1)==-1)       /* thread, initailized semaphore to 1 */
        err("sem_init - thread");

    status=pthread_create(&tid1,NULL,fun,&loop);
    if(status!=0)
        err("tid1");
    status=pthread_create(&tid2,NULL,fun,&loop);
    if(status!=0)
        err("tid2");

    if(pthread_join(tid1,NULL)!=0)
        err("join tid1");
    if(pthread_join(tid2,NULL)!=0)
        err("join tid2");

    printf("glob = %d\n",glob);
    exit(EXIT_SUCCESS);
}
